package cn.tedu._05weibo.controller;

import cn.tedu._05weibo.common.response.JsonResult;
import cn.tedu._05weibo.common.response.StatuCode;
import cn.tedu._05weibo.mapper.UserMapper;
import cn.tedu._05weibo.pojo.dto.UserLoginDTO;
import cn.tedu._05weibo.pojo.dto.UserRegDTO;
import cn.tedu._05weibo.pojo.entity.User;
import cn.tedu._05weibo.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;
import java.util.Date;
/*
Slf4j
日志注解，用于打印日志
 */
/*
Api注解调整控制器类名在knife4j文档中的显示名称
 */
@Api(tags="01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    /*
    1.注册功能:
     */
    @ApiOperation(value="注册功能")
    @PostMapping("reg")
    public JsonResult reg(@RequestBody @Validated UserRegDTO userRegDTO){
        System.out.println("userRegDTO:"+userRegDTO);
        User user=new User();
        UserVO userVO = userMapper.selectByUsername(userRegDTO.getUsername());
        log.debug("userVO="+userVO);
        if(userVO!=null){
           // return new JsonResult(1002,"用户名被占用");
            return new JsonResult(StatuCode.USERNAME_EXISTS);
        }
        BeanUtils.copyProperties(userRegDTO,user);
        user.setCreated(new Date());
        log.debug("user="+user);
        userMapper.insertUser(user);
        return JsonResult.ok();
    }
    /*
    2.登录功能：
     */
    @ApiOperation(value="登录功能")
    @PostMapping("login")
    public JsonResult login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        System.out.println("userLoginDTO:"+userLoginDTO);
        UserVO userVO=userMapper.selectByUsername(userLoginDTO.getUsername());
        log.debug("userVO="+userVO);
        if(userVO!=null){
            if(userVO.getPassword().equals(userLoginDTO.getPassword())){
                session.setAttribute("user",userVO);
                return JsonResult.ok();
            }
            return new JsonResult(StatuCode.PASSWORD_ERROR);
        }
        return new JsonResult(StatuCode.USERNAME_ERROR);

    }
    /*
    3.获取当前用户功能
     */

    @ApiOperation(value="查询用户功能")
    @GetMapping("currentUser")
    public JsonResult currentUSer(@ApiIgnore HttpSession session){
        UserVO userVO = (UserVO) session.getAttribute("user");
        log.debug("userVO="+userVO);
        return JsonResult.ok(userVO);
    }
    /*
    4.退出功能
     */
    @ApiOperation(value="退出功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session){
        session.removeAttribute("user");
    }
}
